<template>
  <div class="dashboard-container">
    <div class="app-container">
      <PageTools :show-before="true">
        <span slot="before">共 {{ page.total }} 条记录</span>

        <template #after>
          <el-button type="primary" size="mini" @click="exportExcel">导出</el-button>
          <el-button type="primary" size="mini" @click="$router.push('/import')">导入</el-button>
          <el-button icon="plus" type="primary" size="small" @click="showDialog = true">新增员工</el-button>
        </template>
      </PageTools>
      <el-card>
        <el-table v-loading="loading" border :data="list">
          <el-table-column label="序号" sortable="" type="index" />
          <el-table-column label="头像" width="200px">
            <template #default="{row}">
              <img v-imagerror="require('@/assets/common/logo-64.png')" :src="row.staffPhoto" class="avatar" @click="showAvatar(row.staffPhoto)">
            </template>
          </el-table-column>
          <el-table-column label="姓名" sortable="" prop="username" />
          <el-table-column label="工号" sortable="" prop="workNumber" />
          <el-table-column label="聘用形式" sortable="" prop="formOfEmployment" :formatter="formatEmployment" />
          <el-table-column label="部门" sortable="" prop="departmentName" />
          <el-table-column label="入职时间" sortable="" prop="timeOfEntry">
            <template #default="{row}">
              {{ row.timeOfEntry | formatDate }}
            </template>
          </el-table-column>
          <el-table-column label="账户状态" sortable="" prop="enableState">
            <template #default="{row}">
              <!-- switch支持v-model双向绑定的布尔值，其他它就是value 与input 的结合
              这里可不用写data的布尔值，直接写value -->
              <el-switch :value="row.enableState === 1" />
            </template>
          </el-table-column>
          <el-table-column label="操作" sortable="" fixed="right" width="280">
            <template #default="{row}">
              <el-button type="text" size="small" @click="$router.push(`/employees/detail/${row.id}`)">查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="showrole(row.id)">角色</el-button>
              <el-button v-if="checkperm('delEmployee')" type="text" size="small" @click="delEmployee(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination
            layout="prev, pager, next"
            :total="page.total"
            :page-size="page.size"
            @current-change="currentChange"
          />
        </el-row>
      </el-card>
      <addEmployee :show-dialog="showDialog" />
      <!-- 头像二维码 -->
      <el-dialog title="头像" :visible.sync="isShowAvatar ">
        <el-row type="flex" justify="center">
          <canvas ref="avatarQRCode" />
        </el-row>
      </el-dialog>
      <!-- 角色权限 -->
      <AssginRole ref="assignRole" :show-role-dialog.sync="showRoleDialog" :employee-id="employeeId" />
    </div>
  </div>
</template>

<script>
import QRCode from 'qrcode'
import { getEmployeeList, delEmployee } from '@/api/employees'
import EnumEmployee from '@/api/constant/employees'
import { formatDate } from '@/filters'
import addEmployee from './components/add-employee.vue'
import AssginRole from './components/assign-role.vue'
export default {
  components: {
    addEmployee,
    AssginRole
  },

  data() {
    return {
      showDialog: false,
      isShowAvatar: false,
      page: {
        page: 1,
        size: 5,
        total: 0
      },
      list: [], // 员工详细列表
      loading: false,

      showRoleDialog: false,
      employeeId: ''
    }
  },
  created() {
    this.getEmployeeList()
  },
  methods: {
    // checkperm(pointName) {
    //   return this.$store.state.user.userinfo.roles.points.includes(pointName)
    // },
    // 获取员工
    async  getEmployeeList() {
      this.loading = true // 先开启懒加载
      const { rows, total } = await getEmployeeList(this.page)
      // console.log(rows)
      // 假设本地数据库没有 enableState（账户状态） 默认加上
      this.list = rows.map(item => ({ ...item, enableState: item.enableState || 1 }))
      this.page.total = total
      this.loading = false // 最后关闭
    },
    // 点击分页
    currentChange(newpage) {
      // console.log(newpage)
      this.page.page = newpage
      // 随着页码更新页面
      this.getEmployeeList()
    },
    // 格式化数据  行、列、值、下标
    formatEmployment(row, column, cellValue, index) {
      const obj = EnumEmployee.hireType.find(item => Number(item.id) === Number(cellValue))
      return obj ? obj.value : '未知形式'
    },

    // 数据导出
    async exportExcel() {
      // 1.0 数据获取
      const { rows } = await getEmployeeList({ page: 1, size: this.page.total })
      console.log(rows)
      // 2.0excel生成
      // 数据转换 hearder data
      // 上面两个数据按照字典排序 即可
      const dict = {
        '手机号': 'mobile',
        '姓名': 'username',
        '入职日期': 'timeOfEntry',
        '聘用形式': 'formOfEmployment',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName'
      }
      const header = Object.keys(dict)
      // console.log(hearder) // dict的键
      const newData = rows.map(user => {
        return this.obj2Arr(user, dict)
      })
      console.log(newData)
      const { export_json_to_excel } = await import('@/vendor/Export2Excel')
      // 花裤衩写的 ，需要传header和data两个参数，data需要 [[]]
      export_json_to_excel({
        header,
        data: newData
      })
    },
    // 导出新数据处理函数
    obj2Arr(user, dict) {
      const res = [] // 装新数据的
      // console.log(user) // 单挑员工数据 键是英文的
      // 只需要按顺序遍历字典
      for (const key in dict) {
        const enkey = dict[key]
        // console.log(enkey)// 字典的值
        let value = user[enkey] // 拿到对象里的值
        // console.log(value) // 按顺序的员工数据
        // 处理一下 雇佣形式  数据中value 大多= 1
        if (enkey === 'formOfEmployment') {
          const obj = EnumEmployee.hireType.find(item => item.id === value)
          value = obj ? obj.value : '未知形式'
        }
        // 处理一下时间
        if (enkey === 'timeOfEntry' || enkey === 'correctionTime') {
          // 全局定义好的过滤器
          value = formatDate(value)
        }
        res.push(value)
      }
      return res
    },
    // 删除员工
    async  delEmployee(id) {
      await this.$confirm(this.$t('confirmDel'))
      await delEmployee(id) // 删除接口
      this.$message.success('删除成功')
      if (this.list.length === 1 && this.page.page > 1) {
        this.page.page--
      }
      // 重新获取下员工 更新页面
      this.getEmployeeList()
    },
    // 点击头像 弹框
    showAvatar(imgUrl) {
      console.log(imgUrl)
      if (imgUrl) {
        this.isShowAvatar = true
        // 显示弹窗后将图片地址 转变为二维码
        // 弹框在所有信息处理完后再弹，所以要延时处理 否则信息先加载又找不到dom ，就渲染不出来
        this.$nextTick(() => {
          QRCode.toCanvas(this.$refs.avatarQRCode, imgUrl, {
            width: 300,
            color: {
              dark: '#66b1ff'
            }
          })
        })
      }
    },
    // 点击角色 弹框
    async showrole(id) {
      await this.$refs.assignRole.getUserDetail(id)
      this.showRoleDialog = true
      this.employeeId = id
    }
  }
}
</script>
<style lang="scss" scoped>
.avatar{
  object-fit: contain;
  width: 200px;
  height: 130px;
}
</style>
